<?php

// 不再依赖 session，改为基于 token 的认证
header("Content-type: text/html; charset=utf-8");
require_once 'include/baidu/AipSpeech.php';
class api extends spController
{  
    
    function __construct(){
        parent::__construct();  
    }
    
    /**
     * 验证用户登录状态
     * @return string|false 用户ID或false
     */
    private function verifyToken() {
        // 从请求头中获取 token（微信小程序会将header转换为小写）
        $token = '';
        $headers = getallheaders();
        
        // 检查是否存在 Authorization 或 authorization 头
        foreach ($headers as $key => $value) {
            if (strtolower($key) === 'authorization') {
                $token = $value;
                break;
            }
        }
        
        // 如果请求头中没有，尝试从参数中获取
        if (empty($token)) {
            $token = $this->spArgs('token', '');
        }
        
        // 简单验证 token 格式
        if (empty($token) || strpos($token, '_') === false) {
            return false;
        }
        
        // 解析 token 获取用户 ID
        list($userId, $timestamp) = explode('_', $token);
        
        // 验证 token 是否过期（7天有效期）
        if (time() - intval($timestamp) > 7 * 24 * 3600) {
            return false;
        }
        
        return $userId;
    }
    
    /**
     * 生成用户 token
     * @param string $userId 用户ID
     * @return string 生成的 token
     */
    private function generateToken($userId) {
        // 简单的 token 生成规则：用户ID_时间戳
        return $userId . '_' . time();
    }
    /**
     *  ajax接口统一返回
     * @param int $code 状态码 0失败 1成功
     * @param string $msg 提示信息
     * @param array $data 数据
     */
    function ajaxReturn($code=0,$msg='',$data=array()){
        header("Content-type: application/json; charset=utf-8");
        $result = array(
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        );
        echo json_encode($result);
        exit;
    }
    /**
     * 微信登录接口
     */
    function wxlogin() {
        $config = spExt('wechat');
        
        $code = $this->spArgs('code');
        if (!$code) {
            $this->ajaxReturn(0, '参数错误');
        }
        
        // 从配置文件中获取微信小程序的appid和secret
        $appid = $config['appid'];
        $secret = $config['secret'];
        
        // 调用微信接口获取openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        
        // 使用curl调用微信接口
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        
        // 解析微信接口返回的结果
        $wxResult = json_decode($result, true);
        
        // 检查是否获取成功
        if(empty($wxResult['openid'])){
            // 如果获取失败，记录错误信息并使用模拟openid（用于开发环境）
            $errorMsg = isset($wxResult['errmsg']) ? $wxResult['errmsg'] : '获取openid失败';
            
            // 开发环境回退到模拟openid
            $openid = 'wxuser_'.substr(md5($code), 0, 16);
        } else {
            // 获取成功，使用微信返回的openid
            $openid = $wxResult['openid'];
        }
        
        // 检查用户是否已存在
        $userModel = spClass('gyxj_userModel');
        $user = $userModel->find(array('user_id' => $openid));
        
        if (!$user) {
            // 创建新用户
            $userData = array(
                'user_id' => $openid,
                'username' => '用户_' . substr($openid, 0, 8),
                'avatar' => '',
                'level' => 1,
                'points' => 0
            );
            $userModel->create($userData);
            $user = $userData;
        } else {
            // 更新最后登录时间（如果表中有该字段）
            if (isset($user['last_login_time'])) {
                $userModel->update(array('last_login_time' => date('Y-m-d H:i:s')), array('user_id' => $openid));
            }
        }
        
        // 生成token
        $token = $this->generateToken($openid);
        
        $this->ajaxReturn(1, '登录成功', array(
            'openid' => $openid,
            'user_info' => $user,
            'token' => $token  // 返回token给客户端
        ));
    }
    
    /**
     * 更新用户信息
     */
    function updateUserInfo() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $nickName = $this->spArgs('nickName');
        $avatar = $this->spArgs('avatar');
        $gender = $this->spArgs('gender');
        
        if (!$nickName) {
            $this->ajaxReturn(0, '用户名不能为空');
        }
        
        $userModel = spClass('gyxj_userModel');
        $updateData = array(
            'username' => $nickName
        );
        
        if ($avatar) {
            $updateData['avatar'] = $avatar;
        }
        
        $result = $userModel->update($updateData, array('user_id' => $user_id));
        
        if ($result) {
            // 获取更新后的用户信息
            $userInfo = $userModel->find(array('user_id' => $user_id));
            $this->ajaxReturn(1, '更新成功', $userInfo);
        } else {
            $this->ajaxReturn(0, '更新失败');
        }
    }
    
    /**
     * 获取用户信息
     */
    function getUserInfo() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $userModel = spClass('gyxj_userModel');
        $userInfo = $userModel->find(array('user_id' => $user_id));
        
        if ($userInfo) {
            // 检查用户头像是否为空，如果为空则使用picsum.photos生成随机头像
            if (empty($userInfo['avatar'])) {
                // 使用用户ID作为随机种子，确保每个用户获取的头像保持一致
                $randomSeed = crc32($user_id);
                // 生成200x200尺寸的头像
                $userInfo['avatar'] = 'https://picsum.photos/id/' . ($randomSeed % 1000) . '/200/200';
            }
            
            // 获取统计数据
            // 1. 作品数量（帖子数量）
            $postsModel = spClass('gyxj_postsModel');
            $works_count = $postsModel->findCount(array('user_id' => $user_id));
            
            // 2. 获得点赞数（所有帖子的点赞总数）
            $likes_count = 0;
            $posts = $postsModel->findAll(array('user_id' => $user_id), null, 'likes');
            foreach ($posts as $post) {
                $likes_count += intval($post['likes']);
            }
            
            // 3. 粉丝数
            $followModel = spClass('gyxj_user_followModel');
            $followers_count = $followModel->findCount(array('followed_user_id' => $user_id));
            
            // 4. 关注数
            $following_count = $followModel->findCount(array('user_id' => $user_id));
            
            // 将统计数据添加到用户信息中
            $userInfo['works_count'] = $works_count;
            $userInfo['likes_count'] = $likes_count;
            $userInfo['followers_count'] = $followers_count;
            $userInfo['following_count'] = $following_count;
            
            // 获取用户作品列表前4条数据
            $worksList = array();
            if ($works_count > 0) {
                $latestPosts = $postsModel->findSql("SELECT post_id, content as title, views, likes 
                                                FROM gyxj_posts 
                                                WHERE user_id = '{$user_id}' 
                                                ORDER BY created_at DESC 
                                                LIMIT 4");
                
                // 格式化作品数据
                foreach ($latestPosts as $post) {
                    // 为没有封面图的作品生成随机封面
                    $randomSeed = crc32($post['post_id']);
                    $coverImage = 'https://picsum.photos/id/' . ($randomSeed % 1000 + 1000) . '/300/200';
                    
                    $worksList[] = array(
                        'id' => $post['post_id'],
                        'title' => mb_strlen($post['title']) > 15 ? mb_substr($post['title'], 0, 15) . '...' : $post['title'],
                        'coverImage' => $coverImage,
                        'views' => $post['views'],
                        'likes' => $post['likes']
                    );
                }
            }
            
            // 将作品列表添加到用户信息中
            $userInfo['works_list'] = $worksList;
            
            $this->ajaxReturn(1, '获取成功', $userInfo);
        } else {
            $this->ajaxReturn(0, '获取失败');
        }
    }
        /**
     * 添加收藏
     */
    function addFavorite() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $content_type = $this->spArgs('content_type');
        $content_id = $this->spArgs('content_id');
        
        if (!in_array($content_type, ['culture', 'ai']) || !$content_id) {
            $this->ajaxReturn(0, '参数错误');
        }
        
        $favoriteModel = spClass('gyxj_favoritesModel');
        if ($favoriteModel->isCollected($user_id, $content_type, $content_id)) {
            $this->ajaxReturn(0, '已收藏');
        }
        
        $result = $favoriteModel->create([
            'user_id' => $user_id,
            'content_type' => $content_type,
            'content_id' => $content_id,
            'collect_time' => date('Y-m-d H:i:s')
        ]);
        
        if ($result) {
            $this->ajaxReturn(1, '收藏成功');
        } else {
            $this->ajaxReturn(0, '收藏失败');
        }
    }

    /**
     * 取消收藏
     */
    function cancelFavorite() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $content_type = $this->spArgs('content_type');
        $content_id = $this->spArgs('content_id');
        
        $favoriteModel = spClass('gyxj_favoritesModel');
        $condition = [
            'user_id' => $user_id,
            'content_type' => $content_type,
            'content_id' => $content_id
        ];
        
        $result = $favoriteModel->delete($condition);
        if ($result) {
            $this->ajaxReturn(1, '取消收藏成功');
        } else {
            $this->ajaxReturn(0, '取消收藏失败');
        }
    }
    /**
     * AI生成诗词
     */
    function generateAIPoetry() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $theme = $this->spArgs('theme');
        $points_needed = 30; // 消耗积分
        
        // 检查用户积分
        $userModel = spClass('gyxj_userModel');
        $user = $userModel->find(['user_id' => $user_id]);
        if ($user['points'] < $points_needed) {
            $this->ajaxReturn(0, '积分不足，无法生成');
        }
        
        // 模拟AI生成诗词（实际项目中对接AI接口）
        $ai_content = $this->mockAIGenerate($theme);
        
        // 记录AI生成内容
        $aiModel = spClass('gyxj_ai_generationsModel');
        $gen_id = $aiModel->create([
            'user_id' => $user_id,
            'theme' => $theme,
            'content' => $ai_content,
            'points_used' => $points_needed
        ]);
        
        if (!$gen_id) {
            $this->ajaxReturn(0, '生成失败');
        }
        
        // 扣除积分并记录
        $userModel->update(['points' => $user['points'] - $points_needed], ['user_id' => $user_id]);
        $pointsModel = spClass('gyxj_points_recordModel');
        $pointsModel->recordPointsChange($user_id, -$points_needed, 'ai_generate', $gen_id);
        
        $this->ajaxReturn(1, '生成成功', [
            'content' => $ai_content,
            'gen_id' => $gen_id
        ]);
    }

    /**
     * 模拟AI生成内容
     */
    private function mockAIGenerate($theme) {
        $templates = [
            "《{$theme}》\n清风拂{$theme}，明月照九州。\n千古兴亡事，都付笑谈中。",
            "《咏{$theme}》\n{$theme}生幽谷，芬芳自不争。\n静待知音至，共赏此中情。"
        ];
        return $templates[array_rand($templates)];
    }
    /**
     * 获取用户任务列表
     */
    function getTasks() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $tasksModel = spClass('gyxj_tasksModel');
        $userTasksModel = spClass('gyxj_user_tasksModel');
        
        $tasks = $tasksModel->getAvailableTasks();
        foreach ($tasks as &$task) {
            $status = $userTasksModel->getUserTaskStatus($user_id, $task['task_id']);
            $task['user_status'] = $status ? $status['status'] : 0;
        }
        
        $this->ajaxReturn(1, '获取成功', ['tasks' => $tasks]);
    }

    /**
     * 完成任务并领取奖励
     */
    function completeTask() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $task_id = $this->spArgs('task_id');
        
        $tasksModel = spClass('gyxj_tasksModel');
        $userTasksModel = spClass('gyxj_user_tasksModel');
        $userModel = spClass('gyxj_userModel');
        $pointsModel = spClass('gyxj_points_recordModel');
        
        // 检查任务是否存在
        $task = $tasksModel->find(['task_id' => $task_id, 'status' => 1]);
        if (!$task) {
            $this->ajaxReturn(0, '任务不存在或已停用');
        }
        
        // 检查任务状态
        $userTask = $userTasksModel->getUserTaskStatus($user_id, $task_id);
        if ($userTask && $userTask['status'] >= 1) {
            $this->ajaxReturn(0, '任务已完成');
        }
        
        // 更新任务状态
        $data = [
            'user_id' => $user_id,
            'task_id' => $task_id,
            'status' => 1,
            'completed_at' => date('Y-m-d H:i:s')
        ];
        
        if ($userTask) {
            $userTasksModel->update($data, ['id' => $userTask['id']]);
        } else {
            $userTasksModel->create($data);
        }
        
        // 增加积分
        $user = $userModel->find(['user_id' => $user_id]);
        $userModel->update(
            ['points' => $user['points'] + $task['points_reward']],
            ['user_id' => $user_id]
        );
        
        // 记录积分变动
        $pointsModel->recordPointsChange($user_id, $task['points_reward'], 'study', $task_id);
        
        $this->ajaxReturn(1, '任务完成，获得'.$task['points_reward'].'积分', [
            'points' => $user['points'] + $task['points_reward']
        ]);
    }
    /**
     * 获取用户通知
     */
    function getNotifications() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        $page = $this->spArgs('page', 1);
        $notifyModel = spClass('gyxj_notificationsModel');
        
        $notifications = $notifyModel->spPager($page, 20)->findAll(
            ['user_id' => $user_id],
            'created_at DESC'
        );
        
        $this->ajaxReturn(1, '获取成功', [
            'notifications' => $notifications,
            'pager' => $notifyModel->spPager()->getPager()
        ]);
    }

    /**
     * 标记通知为已读
     */
    function readNotification() {
        $user_id = $this->verifyToken();
        if (!$user_id) {
            $this->ajaxReturn(0, '请先登录');
        }
        
        $notify_id = $this->spArgs('notify_id');
        
        $notifyModel = spClass('gyxj_notificationsModel');
        $result = $notifyModel->update(
            ['is_read' => 1],
            ['notify_id' => $notify_id, 'user_id' => $user_id]
        );
        
        if ($result) {
            $this->ajaxReturn(1, '标记成功');
        } else {
            $this->ajaxReturn(0, '标记失败');
        }
    }
    
    /**
     * 获取首页数据
     */
    function getHomePageData() {
        // $user_id = $this->verifyToken();
        
        // 轮播数据 - 从数据库获取
        $carouselModel = spClass('gyxj_carouselModel');
        $carouselList = $carouselModel->findSql("SELECT id, content, author, bg_color1 as bgColor1, bg_color2 as bgColor2 
                                               FROM gyxj_carousel 
                                               WHERE status = 1 
                                               ORDER BY sort_order ASC");
        
        // 如果数据库中没有轮播数据，使用默认数据
        if (empty($carouselList)) {
            $carouselList = array(
                array(
                    'id' => 1,
                    'content' => "飞流直下三千尺，疑是银河落九天",
                    'author' => "李白《望庐山瀑布》",
                    'bgColor1' => "#1D3557",
                    'bgColor2' => "#E63946"
                ),
                array(
                    'id' => 2,
                    'content' => "床前明月光，疑是地上霜",
                    'author' => "李白《静夜思》",
                    'bgColor1' => "#E63946",
                    'bgColor2' => "#FFB703"
                ),
                array(
                    'id' => 3,
                    'content' => "但愿人长久，千里共婵娟",
                    'author' => "苏轼《水调歌头》",
                    'bgColor1' => "#1D3557",
                    'bgColor2' => "#A8DADC"
                )
            );
        }
        
        // 文化分类 - 从数据库获取
        $categoryModel = spClass('gyxj_culture_categoriesModel');
        $categoryList = $categoryModel->findSql("SELECT id, name, icon, color 
                                                FROM gyxj_culture_categories 
                                                WHERE status = 1 
                                                ORDER BY sort_order ASC");
        
        // 为每个分类获取内容数量
        $contentModel = spClass('gyxj_cultural_contentModel');
        $cultureCategories = array();
        foreach ($categoryList as $category) {
            // 将分类ID转换为对应的中文名称用于查询
            $categoryNameMap = array(
                'poetry' => '诗词',
                'idiom' => '成语',
                'classics' => '古籍',
                'ar' => 'AR体验'
            );
            
            $categoryName = isset($categoryNameMap[$category['id']]) ? $categoryNameMap[$category['id']] : $category['id'];
            $count = $contentModel->findCount(array('category' => $categoryName));
            
            $cultureCategories[] = array(
                'id' => $category['id'],
                'name' => $category['name'],
                'count' => $count,
                'icon' => $category['icon'],
                'color' => $category['color']
            );
        }
        
        // 如果数据库中没有分类数据，使用默认数据
        if (empty($cultureCategories)) {
            $cultureCategories = array(
                array(
                    'id' => "poetry",
                    'name' => "诗词",
                    'count' => 286,
                    'icon' => "/images/icons/poetry.png",
                    'color' => "rgba(230, 57, 70, 0.15)"
                ),
                array(
                    'id' => "idiom",
                    'name' => "成语",
                    'count' => 154,
                    'icon' => "/images/icons/idiom.png",
                    'color' => "rgba(29, 53, 87, 0.15)"
                ),
                array(
                    'id' => "classics",
                    'name' => "古籍",
                    'count' => 42,
                    'icon' => "/images/icons/classics.png",
                    'color' => "rgba(255, 183, 3, 0.15)"
                ),
                array(
                    'id' => "ar",
                    'name' => "AR体验",
                    'count' => 18,
                    'icon' => "/images/icons/ar-icon.png",
                    'color' => "rgba(168, 218, 220, 0.3)"
                )
            );
        }
        
        // 热门内容
        $trendingContent = $contentModel->findSql("SELECT id, title, category, source_image as image, views, likes 
                                                    FROM gyxj_cultural_content 
                                                    ORDER BY views DESC 
                                                    LIMIT 8");
        
        // 如果没有从数据库获取到数据，使用模拟数据
        if (empty($trendingContent)) {
            $trendingContent = array(
                array(
                    'id' => 101,
                    'title' => "春季相关的经典诗句赏析",
                    'category' => "诗词",
                    'image' => "/images/content/spring.png",
                    'views' => 2458,
                    'likes' => 326
                ),
                array(
                    'id' => 102,
                    'title' => "《论语》中的智慧名言解读",
                    'category' => "古籍",
                    'image' => "/images/content/analects.png",
                    'views' => 1892,
                    'likes' => 254
                ),
                array(
                    'id' => 103,
                    'title' => "容易用错的成语辨析",
                    'category' => "成语",
                    'image' => "/images/content/idioms.png",
                    'views' => 1567,
                    'likes' => 198
                ),
                array(
                    'id' => 104,
                    'title' => "唐诗宋词中的月亮意象",
                    'category' => "诗词",
                    'image' => "/images/content/moon.png",
                    'views' => 1245,
                    'likes' => 210
                )
            );
        }
        
        // 获取用户积分（如果用户已登录）
        $points = 0;
        // if ($user_id) {
        //     $userModel = spClass('gyxj_userModel');
        //     $user = $userModel->find(array('user_id' => $user_id));
        //     $points = $user['points'] ?? 0;
        // }
        
        $this->ajaxReturn(1, '获取成功', array(
            'carouselList' => $carouselList,
            'cultureCategories' => $cultureCategories,
            'trendingContent' => $trendingContent,
            'points' => $points
        ));
    }
    
    /**
     * 获取文化分类内容
     */
    function getCategoryContent() {
        $user_id = $this->verifyToken();
        $category = $this->spArgs('category');
        $page = $this->spArgs('page', 1);
        $pageSize = 10;
        
        $contentModel = spClass('gyxj_cultural_contentModel');
        $where = array();
        if (!empty($category)) {
            $where['category'] = $category;
        }
        
        $contentList = $contentModel->spPager($page, $pageSize)->findAll(
            $where,
            'create_time DESC'
        );
        
        $this->ajaxReturn(1, '获取成功', array(
            'contentList' => $contentList,
            'pager' => $contentModel->spPager()->getPager()
        ));
    }
}